package com.self.serviceedu.controller.front;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.self.commonutils.JwtUtils;
import com.self.commonutils.R;
import com.self.commonutils.ordervo.CourseWebVoOrder;
import com.self.serviceedu.client.OrderClient;
import com.self.serviceedu.entity.EduCourse;
import com.self.serviceedu.entity.chapter.ChapterVo;
import com.self.serviceedu.entity.frontvo.CourseFrontVo;
import com.self.serviceedu.entity.frontvo.CourseWebVo;
import com.self.serviceedu.service.EduChapterService;
import com.self.serviceedu.service.EduCourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/eduservice/coursefront")
@CrossOrigin
public class CourseFrontController {

    @Autowired
    private EduCourseService courseService;

    @Autowired
    private EduChapterService chapterService;

    @Autowired
    private OrderClient orderClient;

    //条件查询带分页查询课程
    @PostMapping("getFrontCourseList/{page}/{limit}")
    public R getFrontCourseList(
            @PathVariable("page") long page,
            @PathVariable("limit") long limit,
            @RequestBody(required = false) CourseFrontVo courseFrontVo){

        Page<EduCourse> pageCourse = new Page<>(page, limit);
        Map<String,Object> map = courseService.getCourseFrontList(pageCourse,courseFrontVo);

        //返回分页所有数据
        return R.ok().data(map);
    }

    //课程详情
    @GetMapping("getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable("courseId") String courseId, HttpServletRequest request){

        //1.根据课程Id，编写SQL语句查询课程信息
        CourseWebVo courseWebVo = courseService.getBaseCourseInfo(courseId);

        //2.根据课程ID查询章节和小节
        List<ChapterVo> chapterVoList = chapterService.getChapterVideoByCourseId(courseId);

        //3. 根据课程Id和用户Id查询当前课程是否已经支付过了
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        boolean isBuy = orderClient.isBuyCourse(courseId, memberId);


        return R.ok().data("courseWebVo",courseWebVo).data("chapterVoList",chapterVoList).data("isBuy",isBuy);
    }

    //根据课程ID查询课程信息
    @PostMapping("getCourseInfoOrder/{courseId}")
    public CourseWebVoOrder getCourseInfoOrder(
            @PathVariable("courseId") String courseId){

        CourseWebVo courseInfo = courseService.getBaseCourseInfo(courseId);
        //将courseInfo的属性赋给CourseWebVoOrder
        CourseWebVoOrder courseWebVoOrder = new CourseWebVoOrder();
        BeanUtils.copyProperties(courseInfo,courseWebVoOrder);

        return courseWebVoOrder;
    }

}
